import { bearing, distance } from '@/geom/great-circle'
import { getEntityMap } from '../../base'
import type { Waypoint } from '../../waypoint'
import type { ATSRoute, ATSRouteSegment } from '../types'
import { getWaypointATSRouteSet } from '../atsroute-index'

export interface ATSRouteSegmentInfo {
  start: string
  end: string
  length: number
  course: number
  enable: boolean
}

export interface ATSRouteInfo {
  id: string
  length: number
  segmentList: ATSRouteSegmentInfo[]
  oppositeSegmentList: ATSRouteSegmentInfo[]
}

export function getATSRouteInfo(r: ATSRoute): ATSRouteInfo {
  return atsRouteInfo(r)
}
function atsRouteInfo(r: ATSRoute): ATSRouteInfo {
  const wpts = getEntityMap<Waypoint>('Waypoint')
  const segmentList = r.segmentList.map((e) => segmentInfo(e, wpts))
  const oppositeSegmentList = r.oppositeSegmentList.map((e) => segmentInfo(e, wpts))
  let length = 0
  for (const seg of segmentList) {
    length += seg.length
  }
  length = Math.floor(length)
  for (const seg of segmentList) {
    seg.length = Math.floor(seg.length)
  }
  for (const seg of oppositeSegmentList) {
    seg.length = Math.floor(seg.length)
  }
  return {
    id: r.id,
    length,
    segmentList,
    oppositeSegmentList
  }
}

function segmentInfo(s: ATSRouteSegment, wpts: Record<string, Waypoint>): ATSRouteSegmentInfo {
  const wpt0 = wpts[s.start]
  const wpt1 = wpts[s.end]
  let course = bearing(wpt0.location, wpt1.location)
  if (course < 0) {
    course += 360
  }
  return {
    start: s.start,
    end: s.end,
    length: distance(wpt0.location, wpt1.location),
    course,
    enable: s.enable
  }
}

export function getWaypointATSRouteInfoList(wpt: string): ATSRouteInfo[] {
  const s = getWaypointATSRouteSet(wpt)
  if (!s) {
    return []
  }
  const ret: ATSRouteInfo[] = []
  for (const r of s) {
    ret.push(getATSRouteInfo(r))
  }
  return ret
}
